<template>
  <Upload 
    id="import"
    :action="requestPath"
    :show-upload-list="false"
    :headers="headers"
    :accept="accepts"
    :on-progress="onProgress"
    :on-success="onSuccess"
    :on-error="onError"
  >
    <Button type="primary" :disabled="isUploading" :loading="isUploading">{{ btnText }}</Button>
  </Upload>
</template>

<script>
export default {
  name: 'import',
  props: {
    // 默认接受 .xlsx .xls两种文件类型
    accepts: {
      type: String,
      default: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    },
    requestPath: {
      type: String,
      default: '',
      required: true
    },
    btnText: {
      type: String,
      default: '导入'
    },
    successCallback: {
      type: Function,
      default: _ => _
    }
  },
  data() {
    return {
      isUploading: false,
      headers: {
        Authorization: `Bearer ${ localStorage.Authorization || '' }`
      }
    }
  },
  methods: {
    onProgress() {
      this.isUploading = true
    },
    onSuccess(response, file, fileList) {
      if (response?.success === false) {
        this.isUploading = false
        this.$message.error({
          content: response?.message || '导入失败',
          duration: 3
        })
        return
      }
      this.isUploading = false
      this.successCallback && this.successCallback({ response, file, fileList })
      this.$emit('importSuccess', { response, file, fileList })
      this.$message.success(response?.data || '导入成功')
    },
    onError(error, file, fileList) {
      this.isUploading = false
      this.$message.error({
        content: file?.message || error?.message || '导入失败',
        duration: 3
      })
    }
  }
}
</script>

<style lang="less">
#import {
  display: flex;
  align-items: center;
}
</style>
